package assets_withdraw

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/pay"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/pay/base"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"
	xerrors2 "gitee.com/liuxuezhan/ar-platform/admin-api/pkg/xerrors/assets"
	"gitee.com/liuxuezhan/ar-platform/base-common/headInfo"
	"gitee.com/liuxuezhan/ar-platform/base-common/pkg/xcode"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/assetsClient/rpc"
	"github.com/fatih/structs"
	"github.com/zeromicro/go-zero/core/logx"
)

type PayWithDrawLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

// c端财务管理页面--提现出款
func NewPayWithDrawLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PayWithDrawLogic {
	return &PayWithDrawLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PayWithDrawLogic) PayWithDraw(req *types.PayWithDrawReq) (resp *types.PayWithDrawRes, err error) {
	UserId := headInfo.GetTokenUid(l.ctx)
	if UserId == 0 {
		return nil, xcode.UserNotFound
	}
	rpc_req := &rpc.PassWithDrawReq{
		OrderNo:   req.Order_nos,
		ChannelId: req.Channel_id,
		Remark:    req.Lock_remark,
		ReqHead: &rpc.Head{
			UseId: UserId,
		},
	}
	// 发送请求
	rpc_resp, err := l.svcCtx.AssetsRpc.PayWithdraw.WithdrawPass(l.ctx, rpc_req)
	if err != nil {
		return nil, err
	}

	if req.Channel_id != 0 {
		if rpc_resp.Order.Channel[req.Channel_id] == nil {
			return nil, xerrors2.ErrWithdrawPayNoChannel
		}
		// 调用第三方支付接口
		config := base.Config{
			MappingCode: rpc_resp.Order.Channel[req.Channel_id].MappingCode,
			Url:         rpc_resp.Order.Channel[req.Channel_id].Url,
			SecretKey:   rpc_resp.Order.Channel[req.Channel_id].SecretKey,
			MerchantId:  rpc_resp.Order.Channel[req.Channel_id].MerchantId,
			PrivateKey:  rpc_resp.Order.Channel[req.Channel_id].PrivateKey,
			AppId:       rpc_resp.Order.Channel[req.Channel_id].AppId,
			ReturnUrl:   rpc_resp.Order.Channel[req.Channel_id].ReturnUrl,
			NotifyUrl:   rpc_resp.Order.Channel[req.Channel_id].NotifyUrl,
			AppCode:     rpc_resp.Order.Channel[req.Channel_id].AppCode,
		}
		res, err := pay.NewFactory(config).Withdraw(l.ctx, structs.Map(rpc_resp))
		if err != nil {
			return nil, err
		}

		// 记录第三方支付渠道订单号
		if res.ThirdOrderSn != "" {
			_, err = l.svcCtx.AssetsRpc.PayWithdraw.WithdrawOrderIdUpdate(l.ctx, &rpc.WithdrawOrderIdUpdateReq{
				OrderNo: res.OrderSn, OrderId: res.ThirdOrderSn,
			})
			if err != nil {
				return nil, err
			}
		}
	}

	// 处理请求返回的结果
	// 解析、组合数据
	resp = &types.PayWithDrawRes{}
	if rpc_resp.Order != nil {

	}
	return
}
